from datetime import datetime

from src.utils import CommonUtils, BatchUtils
from src.utils.LogUtils import Logger
import uuid
import requests

class SyncReportDataInfo:
    def __init__(self, logger, localDb, dataCenterDb, fcdb):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb
        self.fcdb = fcdb
        self.size = 1000
        self.total = 0

    # 获取境外评级数据
    def __queryReportInfo__(self):
        sql = """SELECT last_release_time,title,type_level1, type_level2, uuid, file_id FROM research_report 
                 WHERE ver = 0 and release_status = 1 and audit_status = 1
                 ORDER BY last_release_time  """
        return self.dataCenterDb.Query(sql)

    # 获取境外评级数据
    def __queryReportInfoByDate__(self,date):
        sql = """SELECT last_release_time,title,type_level1, type_level2 , uuid, file_id FROM research_report 
                 WHERE ver = 0 and release_status = 1 and audit_status = 1 and last_release_time > %s
                 ORDER BY last_release_time  """
        return self.dataCenterDb.Query(sql, date)

    # 获取code编号
    def __queryCode__(self, typeName):
        sql = """SELECT code,father_code FROM credit_research_type 
                 WHERE  name = %s LIMIT 1 """
        return self.localDb.QueryOne(sql, typeName)

    # 写入到固收库
    def __updateaDataInfo__(self, updateData):
        delSql = """ delete from credit_research_report where uuid = %s"""
        self.localDb.Query(delSql, updateData["uuid"])

        # 文件上传
        sql = """
            INSERT INTO `credit_research_report` (`title`, `publish_date`, `update_time`, `status`, `file_name`, `type_l1`, `type_l2`, `uuid`)
             VALUES (%s, %s, %s, 1, %s, %s, %s, %s);
        """
        param_list = []
        param_list.append(updateData["title"])
        param_list.append(updateData["last_release_time"])
        param_list.append(updateData["last_release_time"])
        param_list.append(updateData["file_name"])
        param_list.append(updateData.get("type_l1",""))
        param_list.append(updateData.get("type_l2",""))

        param_list.append(updateData["uuid"])
        return self.localDb.ExecNoneQuery(sql, param_list)

    # 获取最新同步时间
    def __querySyncTimeLine__(self):
        sql = """SELECT DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s') AS update_time from credit_research_report 
                 order by update_time desc LIMIT 1 """
        return self.localDb.QueryOne(sql)

    # 文件读写
    def __pdfUpd__(self, fileId, title):
        # url = 'http://101.227.67.188:8889/researchReport/reportFile?fileId='+str(fileId)
        # res = requests.get(url)
        fileName = title + """.pdf"""
        # localUrl = "/home/pdf" + fileName
        # with open(localUrl, "wb") as code:
        #     code.write(res.content)
        # minioClient = MinioClient()
        # minioClient.upload_file('test', fileName, localUrl)
        return fileName

    # 同步入口
    def sync(self):
        self.logger.info("报告数据同步")
        date = self.__querySyncTimeLine__();
        # 加载需要同步的数据
        if date is None:
            dataInfo = self.__queryReportInfo__()
        else:
            dataInfo = self.__queryReportInfoByDate__(date["update_time"])
        for r in dataInfo:
            r["file_name"] = self.__pdfUpd__(r["file_id"],r["title"],)
            codeInfo = self.__queryCode__(r["type_level2"])
            if codeInfo is not None:
                r["type_l1"] = codeInfo["father_code"]
                r["type_l2"] = codeInfo["code"]
            self.__updateaDataInfo__(r)




